import { TodoType } from './store';
export type ActionType = { type: string; payload?: string | boolean | TodoType };
function reducer(state: TodoType[], action: ActionType) {
  switch (action.type) {
    case 'add':
      return state.concat(action.payload as TodoType);
    case 'remove':
      return state.filter((todo) => {
        return todo.id !== (action.payload as string);
      });
    case 'update':
      return state.map((todo) => {
        return todo.id === (action.payload as TodoType).id ? (action.payload as TodoType) : todo;
      });
    case 'checkAll':
      return state.map((todo) => {
        return { ...todo, done: action.payload as boolean };
      });
    case 'clearDone':
      return state.filter((todo) => !todo.done);
    default:
      throw new Error('action type error');
  }
}

export default reducer;
